﻿using System;
using System.Collections.Generic;
using System.Diagnostics;



namespace FineCollection.Const
{

    internal static class ConstUtils
    {
        

        internal struct ArrayWithCount<T>
        {
            public T[] array;
            public int count;
        }



        internal static ArrayWithCount<T> CollectItemsIntoArray<T>(IEnumerator<T> enumerator, int estimatedCount) 
        {
            if (estimatedCount < 1)
                estimatedCount = 16; 

            T[] theArray = new T[estimatedCount];
            int k = 0;
            while (enumerator.MoveNext())
            {
                if (k == theArray.Length-1)
                {
                    int oldSize = theArray.Length;
                    int newSize;
                    if (oldSize <= 16)
                        newSize = oldSize >> 1;
                    else if (oldSize < 256)
                        newSize = oldSize + (oldSize >> 1);
                    else 
                        newSize = oldSize + (oldSize >> 2);
                    Debug.Assert(k+1 < newSize);
                    Array.Resize(ref theArray, newSize);
                }

                theArray[k] = enumerator.Current;
                k++;
            }
            return new ArrayWithCount<T> {array = theArray, count = k};
        }


    }


}